

window.onload=function(){
    $('.loading').hide();
};

//默认加载数据
$.get(SITEURL + 'wechat/shop/getData',function(datas){
    //console.log(datas);
    if(datas.code!=0){
        localStorage.setItem('errorinfo',datas.msg);
        window.location = SITEURL + 'wechat/shop/fail';
        return false;
    }

    //转化为json
    var jsons = datas;
    if(datas.data.region.first==1){
        $('.ydbg').show();
        $('.ahide').hide();
        $('.ydbg').click(function(){
            $('.ydbg').hide();
            if(jsons.data.region.first==1){
                $('.lou-bg').show();
                $('.ahide').show();
                $('.lou-bg').click(function(){
                    $('.lou-bg').hide();
                });

            }
        });
    }else{
        //判断是否弹出楼宇列表
        if(jsons.data.region.first==1){
            $('.ahide').show();
        }
    }

    //设置大楼名称
    $('.search-wp div').text(jsons.data.region.region_name);
    $('#regionId').val(jsons.data.region.region_id);


    //判断是否出现评价
    if(jsons.data.comment>0){
        pingLun(jsons.data.comment);
    }



    //添加头部本周列表
    var dayInfo = jsons.data.menu;
    var dayLeng = dayInfo.length;
    var dayHtml = '';

    for(var i=0;i<dayLeng;i++){
        var li = i==0?'<li key="'+i+'" time="'+dayInfo[i].menu_time+'" date="'+dayInfo[i].menu_date+'" token="'+dayInfo[i].token+'" class="on">':'<li key="'+i+'" time="'+dayInfo[i].menu_time+'" date="'+dayInfo[i].menu_date+'" token="'+dayInfo[i].token+'">';
        var title = dayInfo[i].menu_title;

        var jieday = title?'<span class="'+(title=='已截止'?'col':'')+'">'+title+'</span>':'<span>'+dayInfo[i].menu_date+'</span>';
        dayHtml+= (li+'<span>'+dayInfo[i].menu_week+'<var></var></span>'+jieday+'<em></em></li>');
    }

    $('.nav-list').html(dayHtml);
    clickDay();

    for(var i=0;i<dayInfo.length;i++){
        var order = dayInfo[i].order;

        if(order.length>0){
            $('.nav-list li').eq(i).find('var').show();
        }
    }

    var todaySet = dayInfo[0].order;

    if(todaySet.length>0){
        todayHasSet(todaySet);
    }else{
        $('.yiding-wp').hide();
    }

    //显示已售罄和已截止的效果

    var remind = dayInfo[0].remind;

    if(dayInfo[0].remind&&remind.title){
        sellOut(remind.time,remind.title,remind.desc);
    }

    //添加菜品信息
    if(dayInfo[0].goods){

        var token = $('.nav-list').find('.on').attr('token');
        addGoods(dayInfo[0].goods,token);
    }

    //根据localstage设置购物车
    setData();

});

//设置评论弹框

function pingLun(id){
    $.post(SITEURL + 'wechat/shop/getComment',{'comment_id':id},function(data){
        $('.ping').show();
        var datas = data.data;
        var nowgoods = datas.goods;
        $('.kt').attr('src',nowgoods.goods_image);
        $('.ping-wt').text(nowgoods.goods_name);
        $('#xin').val(nowgoods.id);

        if(datas.next){
            $('.next-ping').css({'display':'flex'});
            $('.next-ping').find('p').text(datas.next.goods_name);
            $('.next-ping').attr('nextid',datas.next.id);

            $('.next-ping').click(function(){
                pingLun(datas.next.id);
            });
        }else{
            $('.next-ping').hide();
        }
    });
}

//大厦方法
var Build={
    //添加楼宇大厦列表
    addBuilding:function(){
        var _this = this;
        $.get(SITEURL + 'wechat/shop/getRegionList',function(data){
            if(data.code!=0){
                localStorage.setItem('errorinfo',data.msg);
                window.location = SITEURL + 'wechat/shop/fail';
                return false;
            }
            var html = '';
            var ds = data.data;
            var leng = ds.length||'';
            for(var i=0;i<leng;i++){
                html+= '<li sid="'+ds[i].region_id+'"><p>'+ds[i].region_name+'</p></li>';
            }
            $('.ahide-wrap').html(html);
            _this.checkBulid();
        });
    },
    //关闭大厦列表
    close:function(){
        $('.ahide-c').find('.quxiao').click(function(){
            $('.ahide').hide();
        });
    },
    //清空输入框方法
    clearInput:function(){
        $('.ahide-c').find('img').click(function(){
            $('#building').val('');
        });
    },
    //选中楼宇方法
    checkBulid:function(){
        $('.ahide-wrap li').each(function(i,e){
            $(e).click(function(){
                var str = $(e).find('p').text();
                $('.ahide').hide();
                $('.search-wp div').text(str);

                if($('#regionId').val()!=$(e).attr('sid')){
                    localStorage.removeItem("cart");
                    $('.shu').text(0);
                    $('.car-list').empty();
                }

                $('#regionId').val($(e).attr('sid'));

                $.post(SITEURL + 'wechat/shop/getCurrentData',{region_id:$(e).attr('sid'),menu_date:$('.nav-list').find('.on').attr('time'),menu_key:$('.nav-list').find('.on').attr('key')},function(data){
                    if(data.code!=0){
                        localStorage.setItem('errorinfo',data.msg);
                        window.location = SITEURL + 'wechat/shop/fail';
                        return false;
                    }
                    var datas = data;
                    var token = $('.nav-list').find('.on').attr('token');
                    addGoods(datas.data.goods,token);
                    var remind = datas.data.remind;
                    sellOut(remind.time,remind.title,remind.desc);

                });
            });
        });
    },
    //显示大厦
    showBulid:function(){
        $('.search-wp').click(function(){
            $('.ahide').show();
        });
    },
    //输入选择
    inputFun:function(){
        var _this = this;
        $("#building").bind('input propertychange',function(){
            var val = $(this).val();
            $.get(SITEURL + 'wechat/shop/getRegionList?keyword='+val,function(data){
                if(data.code!=0){
                    localStorage.setItem('errorinfo',data.msg);
                    window.location = SITEURL + 'wechat/shop/fail';
                    return false;
                }
                var html = '';
                var ds = data.data;
                var leng = ds.length;
                for(var i=0;i<leng;i++){
                    html+= '<li sid="'+ds[i].region_id+'"><p>'+ds[i].region_name+'</p></li>';
                }
                $('.ahide-wrap').html(html);
                _this.checkBulid();
            });
        });
    },
    //初始化方法
    init:function(){
        this.showBulid();
        this.inputFun();
        this.addBuilding();
        this.close();
        this.clearInput();
    }
};

//初始化大厦方法
Build.init();




//点击购物车
$('.car').click(function(){
    $('.car-bg').show();
    $('.car-wp').show();
});
//关闭购物列表
$('.car-wp .close').click(function(){
    $('.car-bg').hide();
    $('.car-wp').hide();
});

//点击结算
$('.car-btns').click(function(){
    var obj = {};

    obj.region = {
        region_id:$('#regionId').val(),
        region_name:$('.search-wp').find('div').eq(0).text()
    };

    obj.data = [];

    $('.car-list dt').each(function(i,e){
        var act = {};
        act.menu_date = $(e).attr('date');
        act.menu_week = $(e).attr('week');
        act.token = $(e).attr('token');
        act.goods = [];

        $(e).nextUntil('dt').each(function(m,n){
            var goods = {};
            goods.goods_id = $(n).attr('goodsid');
            goods.goods_num = $(n).find('em').text();
            goods.goods_name = $(n).find('p').text();
            act.goods.push(goods);
        });
        obj.data.push(act);
    });

    if($('.car-list dt').length<1){
        salert('请选择菜品');
    }else{
        var str = JSON.stringify(obj);
        localStorage.setItem('cart',str);
        window.location = SITEURL + 'wechat/shop/confirmOrder/';

    }


});


//关闭点评框

$('.ping-tit span').click(function(){
    $('.ping').hide();
});


//选中黑心
$('.ping-xin span').each(function(i,e){
    $(e).click(function(){
        var val = 0;
       /* if($(e).hasClass('on')){
            $('.ping-xin span').each(function(c,m){
                if(c>=i){
                    $(m).removeClass('on');
                }
            });
            val = i;
        }else{*/
            $('.ping-xin span').removeClass('on');
            $('.ping-xin span').each(function(c,m){
                if(c<=i){
                    $(m).addClass('on');
                }
            });

            val = i+1;
        //}

        $('#pxin').val(val);
    });
});


/* 提交评论 */
$('#pingId').click(function(){
    if($('#pxin').val()==0){
        salert('请选择星级');
        return;
    }
    if($.trim($('#pingText').val())==''){
        salert('请填写评论内容');
        return;
    }

    $.post(SITEURL + 'wechat/shop/submitComment',{comment_id:$('#xin').val(),comment:$.trim($('#pingText').val()),star:$('#pxin').val()},function(data){
        if(data.code==0){
            $('#pxin').val(0);
            $('#pingText').val('');
            $('.ping').hide();
        }else{
            salert(data.msg);
        }
    });
});


//购物车操作
var Car = {
    //单品添加效果
    addDan:function(a){
        if(!$(a).parents('li').hasClass('qing')){
            var n = parseInt($(a).parents('li').attr('total'));
            if(n>0){
                $(a).parents('li').attr('total',n-1);

                $(a).parents('li').find('.a-surplus').text(n-1);
                n-1>=10?$(a).parents('li').find('.surplus').hide():$(a).parents('li').find('.surplus').show();

                var prevTxt = parseInt($(a).prev().text());
                var num = prevTxt+1;
                $(a).prev().text(num);
                var caiName = $(a).parent().prev().text();
                var id = $(a).parent().attr('goodid');
                var tokens = $('.nav-list').find('.on').attr('token');
                var dates = $('.nav-list').find('.on').attr('date');
                var txts = $('.nav-list').find('.on').find('span').eq(0).text();

                this.setNum(caiName,num,tokens,dates,txts,id,n);
                //计算份数
                fen(1);
            }else{
                salert('暂无存货');
            }

        }

    },
    //单品减少效果
    jianDan:function(a){
        if(!$(a).parents('li').hasClass('qing')) {

            var prevTxt = parseInt($(a).next().text());
            if(prevTxt>0){
                var n = parseInt($(a).parents('li').attr('total'));
                $(a).parents('li').attr('total',n+1);

                $(a).parents('li').find('.a-surplus').text(n+1);
                n+1>=10?$(a).parents('li').find('.surplus').hide():$(a).parents('li').find('.surplus').show();
                //计算份数
                fen(-1);
            }else{
                salert('您还没有点菜');
            }
            var num = prevTxt > 0 ? prevTxt - 1 : 0;
            $(a).next().text(num);
            var caiName = $(a).parent().prev().text();
            var id = $(a).parent().attr('goodid');
            var tokens = $('.nav-list').find('.on').attr('token');
            var dates = $('.nav-list').find('.on').attr('date');
            var txts = $('.nav-list').find('.on').find('span').eq(0).text();
            this.setNum(caiName,num,tokens,dates,txts,id,n+1);
        }
    },
    //购物车单列表添加数据，参数为 name:菜品名, n:点菜数量，token，date:12月8日,week：周三,goodsid,total:库存
    setNum:function(name,n,token,date,week,goodsid,total){
        var dt = $('.car-list').find('dt[token='+token+']');
        var dds = $('.car-list').find('dd[goodsid='+goodsid+']');
        var dd = '<dd token="'+token+'" goodsid="'+goodsid+'"><p>'+name+'</p><div class="add-cont"><span></span><em>'+n+'</em><span></span></div></dd>';

        if(n==0){
            dds.remove();
            if(dt.nextUntil('dt').length==0){
                dt.remove();
            }
        }else{
            if(dt.length>0){
                dds.length>0?dds.find('em').text(n):dt.after(dd);
            }else{
                var dtHtml = '<dt token="'+token+'" date="'+date+'" week="'+week+'"><span></span>'+week+' '+date+'</dt>';
                $('.car-list').append(dtHtml+dd);
            }
        }

        this.carAdd(goodsid);
    },
    //购物车内加减法
    carAdd:function(id){

        $('.car-list .add-cont').each(function(i,e){
            $(e).find('span').eq(0).unbind();
            $(e).find('span').eq(1).unbind();
            $(e).find('span').eq(0).click(function(){
                var num = parseInt($(this).next().text())-1;
                var n = parseInt($('.cai-list').find('li[caiid='+id+']').attr('total'));
                $(this).next().text(num);
                var t = $(e).parent().attr('token');
                if(num==0){
                    $(e).parent('dd').remove();
                    if($('.car-list').find('dd[token='+t+']').length==0){
                        $('.car-list').find('dt[token='+t+']').remove();
                    }
                }

                $('.cai-list').find('li[caiid='+id+']').attr('total',n+1);
                $('.cai-list').find('li[caiid='+id+']').find('.add-cont').find('em').text(num);

                $('.cai-list').find('li[caiid='+id+']').find('.a-surplus').text(n+1);
                var surplus = $('.cai-list').find('li[caiid='+id+']').find('.surplus');
                n+1>=10?surplus.hide():surplus.show();

                //计算份数
                fen(-1);

            });
            $(e).find('span').eq(1).click(function(){
                var n = parseInt($('.cai-list').find('li[caiid='+id+']').attr('total'));
                var num = parseInt($(this).prev().text())+1;
                if(n>0){
                    $(this).prev().text(parseInt($(this).prev().text())+1);
                    $('.cai-list').find('li[caiid='+id+']').attr('total',n-1);
                    $('.cai-list').find('li[caiid='+id+']').find('.add-cont').find('em').text(num);

                    $('.cai-list').find('li[caiid='+id+']').text(n-1);
                    var surplus = $('.cai-list').find('li[caiid='+id+']').find('.surplus');
                    n-1>=10?surplus.hide():surplus.show();
                    //计算份数
                    fen(1);
                }else{
                    salert('库存不足');
                }
            });
        });
    }
};

var timmer;

function timerFun(num){
    var g = Math.floor(num / 3600);
    var e = Math.floor((num - g * 3600) / 60);
    var f = (num - g * 3600) % 60;
    $('.tips-timer span').eq(0).text(g);
    $('.tips-timer span').eq(1).text(e);
    $('.tips-timer span').eq(2).text(f);
}

//显示已售罄和已截止的效果
function sellOut(time,title,tips){

    if(time){
        $('#sellout').hide();

        $('#selling').show();
        $('.tips-tit').text(title);

        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;

        var cuo = time-timestamp;

        timerFun(cuo);

        timmer = setInterval(function(){
            timerFun(cuo);
            cuo--;
        },1000);
    }else{
        clearInterval(timmer);
        if(title&&tips){
            $('#sellout').show();
            $('#selling').hide();
            $('.tips-all').text(title);
        }else{
            $('#sellout').hide();
            $('#selling').hide();
        }

    }
    $('.tips-gowp').find('span').text(tips);

    //点击提前预定
    $('.tips-gowp').find('span').unbind();
    $('.tips-gowp').find('span').click(function(){
        $('.nav-list').find('.on').next().click();
       
        return;
        /*$('.nav-list li').each(function(i,e){
            if($(e).hasClass('on')){
                console.log(i);
                if(i!=4){
                    $(e).next().click();
                }else{
                    $('.nav-list li').eq(0).click();

                }
                return;
            }
        });*/
    });
}


//添加菜品信息
function addGoods(goods,tk){
    var list = '';

    var leng = goods.length||0;
    for(var i=0;i<leng;i++){
        var txt = goods[i].goods_storage>0?'<li caiid="'+goods[i].goods_id+'" total="'+goods[i].goods_storage+'"><div class="img-wp"><img onclick="caiDeatil('+goods[i].goods_id+')" src="'+goods[i].goods_image+'" /><span class="surplus" style="display:'+(goods[i].goods_storage<10?'block':'none')+'">剩余<em class="a-surplus">'+goods[i].goods_storage+'</em>份</span></div>':'<li class="qing"><div class="img-wp"><img src="'+goods[i].goods_image+'" class="gray" /><span class="btn">售罄</span></div>';
        list+=(txt+'<div class="act-wp"><p>'+goods[i].goods_name+'</p><div class="add-cont" token="'+tk+'" goodid="'+goods[i].goods_id+'"><span onclick="Car.jianDan(this)"></span><em>0</em><span onclick="Car.addDan(this)"></span></div></div><div class="jia-con"><div class="ml"><h4 class="package-tit">套餐包括:</h4><p class="package-cont">'+goods[i].goods_combo+'</p></div><div class="jia-r"><p><span>菜品原价:</span><em class="line">'+goods[i].market_price+'元</em></p><p><span>抢&nbsp;&nbsp;购&nbsp;&nbsp;价:</span><em class="hot">'+goods[i].shop_price+'</em>元</p></div></div><div class="kuai"><img src="'+goods[i].store_logo+'" ><p>'+goods[i].store_slogan+'</p></div></li>');
    }

    $('.cai-list').html(list);

}

//点击菜品图片出现详情
function caiDeatil(id){
    $('.caix').show();
    $.get(SITEURL + 'wechat/shop/getGoodsDetail?goods_id='+id,function(a){
        if(a.code!=0){
            localStorage.setItem('errorinfo',a.msg);
            window.location = SITEURL + 'wechat/shop/fail';
            return false;
        }
        var datas = a.data;
        $('.cai-detail').attr('ids',datas.goods_id);
        $('.cai-detail').find('.img-wp').find('img').attr('src',datas.goods_image);
        $('.cai-d-tit').text(datas.goods_name);
        $('.cai-biao').find('p').text(datas.goods_combo);

        $('.can-edit').html(datas.goods_content);
    });

    $('.cai-detail-close').click(function(){
        $('.caix').hide();
    });
}

//点击周几显示内容
function clickDay(){
    $('.nav-list li').each(function(Index,Element){
        $(Element).click(function(){

            var txt = $(this).attr('time');
            var key = $(this).attr('key');
            $('.nav-list li').removeClass('on');
            $(this).addClass('on');
            var val = $('#regionId').val();
            $.post(SITEURL + 'wechat/shop/getCurrentData',{region_id:val,menu_date:txt,menu_key:key},function(data){
                // if(data.code!=0){
                //     localStorage.setItem('errorinfo',data.msg);
                //     window.location = '404.html';
                //     return false;
                // }
                var datas = data;
                var token = $('.nav-list').find('.on').attr('token');
                addGoods(datas.data.goods,token);
                var todaySet = datas.data.order;
                if(todaySet.length>0){
                    todayHasSet(todaySet);
                }else{
                    $('.yiding-wp').hide();
                }

                var remind = datas.data.remind;
                sellOut(remind.time,remind.title,remind.desc);

                carInfoGoods();
            });
        });
    });
}

//添加今日已经定的菜品
function todayHasSet(data){
    //$('.nav-list').find('.on').find('var').show();
    $('.yiding-wp').get(0).style.display = 'flex';
    $('.yiding-wp ul').find('li').remove();
    var html = '';

    for(var i=0;i<data.length;i++){
        html+='<li>'+data[i]+'</li>';
    }

    $('.yiding-wp ul').html(html);
}


//根据localstage设置购物车
function setData(){
    if(localStorage.getItem('cart')){
        var obj = JSON.parse(localStorage.getItem('cart'));
        var goodsData = obj.data;
        var gl = goodsData.length;
        for(var i=0;i<gl;i++){
            var txt = goodsData[i].menu_date;
            var k = 0;
            $('.nav-list li').each(function(m,n){
                if($(n).attr('date')==txt){
                    k=1;
                }
            });

            if(k==0){
                goodsData.splice(i,1);
            }
        }

        var dlhtml = '';
        var sn = 0;
        for(var i=0;i<goodsData.length;i++){
            dlhtml+='<dt token="'+goodsData[i].token+'" date="'+goodsData[i].menu_date+'" week="'+goodsData[i].menu_week+'"><span></span>'+goodsData[i].menu_week+' '+goodsData[i].menu_date+'</dt>';
            var sl = goodsData[i].goods.length;
            var gs = goodsData[i].goods;
            for(var c=0;c<sl;c++){
                sn += parseInt(gs[c].goods_num);
                dlhtml+='<dd token="'+goodsData[i].token+'" goodsid="'+gs[c].goods_id+'"><p>'+gs[c].goods_name+'</p><div class="add-cont"><span></span><em>'+gs[c].goods_num+'</em><span></span></div></dd>';
            }
        }

        $('.car-list').html(dlhtml);

        $('.car').find('.shu').text(sn);
        $('.car-list dd').each(function(i,e){
            Car.carAdd($(e).attr('goodsid'));
        });

    }
}
//根据购物车内信息添加到菜品上
function carInfoGoods(){
    $('.car-list dd').each(function(Index,Element){
        $('.cai-list').find('.add-cont').each(function(i,e){
            if($(Element).attr('token')==$(e).attr('token')&&$(Element).attr('goodsid')==$(e).attr('goodid')){
                $(e).find('em').text($(Element).find('em').text());
            }
        });
    });
}



//计算份数
function fen(n){
    var shu = parseInt($('.car').find('.shu').text());
    $('.car').find('.shu').text(shu+n);
}





